package com.lqfan.autoAnswerQ.service.wrongSubject.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.lqfan.autoAnswerQ.dao.subjectChoiceType.SubjectChoiceTypeMapper;
import com.lqfan.autoAnswerQ.model.fileType.FileType;
import com.lqfan.autoAnswerQ.model.quesBank.QuesBankModel;
import com.lqfan.autoAnswerQ.model.quesBank.Question;
import com.lqfan.autoAnswerQ.model.subject.HandleImportModel;
import com.lqfan.autoAnswerQ.model.subject.Subject;
import com.lqfan.autoAnswerQ.model.subjectChoiceType.SubjectChoiceType;
import com.lqfan.autoAnswerQ.model.wrongSubject.WrongSubject;
import com.lqfan.autoAnswerQ.dao.wrongSubject.WrongSubjectMapper;
import com.lqfan.autoAnswerQ.service.fileType.IFileTypeService;
import com.lqfan.autoAnswerQ.service.quesBank.IQuestionService;
import com.lqfan.autoAnswerQ.service.subject.ISubjectService;
import com.lqfan.autoAnswerQ.service.subjectType.ISubjectTypeService;
import com.lqfan.autoAnswerQ.service.wrongSubject.IWrongSubjectService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.apache.ibatis.annotations.Delete;
import org.apache.ibatis.annotations.Insert;
import org.apache.ibatis.annotations.Select;
import org.apache.ibatis.annotations.Update;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author zml
 * @since 2020-04-25
 */
@Service
public class WrongSubjectServiceImpl extends ServiceImpl<WrongSubjectMapper, WrongSubject> implements IWrongSubjectService {
    private static final String filePath = System.getProperty("user.dir");
    @Autowired
    IFileTypeService fileTypeService;
    @Autowired
    IQuestionService questionService;
    @Autowired
    ISubjectService subjectService;
    @Autowired
    private ISubjectTypeService subjectTypeService;
    @Autowired
    private SubjectChoiceTypeMapper choiceTypeMapper;
    /**
     * 做错题则插入错题在默认路径下
     * @param questionId
     * @param userId
     * @param subjectId
     * @param confirmNumber //获取更新默认次数会进行统一修改
     * @return
     */
    public int insertWrongSubject(String questionId,String userId,String subjectId,String confirmNumber,Integer isDeleteWrong,String path, String isError,String name){
        boolean checkWrongSubject = checkWrongSubject(userId,subjectId);
        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.eq("id",questionId);
        Question question = questionService.getOne(queryWrapper);
        String src = filePath + "/source/"+3+"/"+ userId + path+question.getQuestionName()+"/";
        if (isError.equals("0")&&checkWrongSubject){
            boolean updateDoNumInit = baseMapper.updateDoNumInit(userId,subjectId);
            if (updateDoNumInit){
                return 8;
            }else {
                return 9;
            }
        }else {
            if (isError.equals("1")||checkWrongSubject){
                //存在错题，更新
                if (isDeleteWrong==0){
                    boolean updateDoNum = updateDoNum(userId,subjectId);
                    if (updateDoNum){
                        //更新成功
                        int deleteWrongSubject = deleteWrongSubject(userId,subjectId,src);
                        return deleteWrongSubject;

                    }else {
                        return 2; //更新错题失败
                    }
                }else {
                    return 7; //禁止删除和更新
                }

            }else {
                WrongSubject wrongSubject = new WrongSubject();


                String f = fileTypeService.selectFilePid(src);
                if (f==null){
                   fileTypeService.saveFileType(src,3,userId);
                }
                wrongSubject.setPath(src);
                wrongSubject.setQuestionId(questionId);
                wrongSubject.setSubjectId(subjectId);
                wrongSubject.setUserId(userId);
                wrongSubject.setConfirmNumber(confirmNumber);
                wrongSubject.setIsDeleteWrong(isDeleteWrong);
                wrongSubject.setName(name);
                //不存在错题，插入
                boolean insertWrong = baseMapper.insertWrongSubject(wrongSubject);
                if (insertWrong){
                    return 1; //插入成功
                }else {
                    return 0; //插入失败
                }
            }
        }

    }

    /**
     * 检查错题是否存在
     * @param userId
     * @param subjectId
     * @return
     */
    public boolean checkWrongSubject(String userId ,String subjectId){
        String checkId = baseMapper.checkWrongSubject(userId,subjectId);
        if (checkId==null){
            return false;
        }else {
            return true;
        }

    }

    /**
     * 每次做的时候进行比对
     * 若答题对得次数相等则删除错题
     */
    public boolean checkRunNum(String userId,String subjectId){
        String checkRunNum = baseMapper.checkRunNum(userId,subjectId);
        if (checkRunNum==null){
            return false;
        }else {
            return true;
        }
    }

    /**
     * 每做一次进行记录
     * 修改目前答题次数
     */

    public boolean updateDoNum(String userId,String subjectId){
        boolean updateDoNum = baseMapper.updateDoNum(userId,subjectId);
        return updateDoNum;
    }

    /**
     * 设置修改操作
     * 更新该用户所有错题得完成错题设置
     * 设置是否允许删除题库 整体更新
     * @param confirmNumber
     * @param userId
     * @return
     */
    public int updateWrongSet(String confirmNumber,String userId,Integer isDeleteWrong){
        boolean updateWrongSet = baseMapper.updateWrongSet(confirmNumber,userId,isDeleteWrong);
        if (updateWrongSet){
            return 1; //修改成功
        }else {
            return 0; //修改失败
        }

    }

    /**
     * 手动删除指定错误题库,需要同时删除文件
     */
    public int deleteWrongProduct(String userId,String productId){
        //检查是否存在该题
        boolean deleteWrongProduct   = baseMapper.deleteWrongProduct(userId,productId);
        if (deleteWrongProduct){
            return 1;  //删除成功
        }else {
            return 0; //删除失败
        }

    }

    /**
     * 自动比对达到数据直接删除题目
     */
    public int deleteWrongSubject(String userId,String subjectId,String path){
        //检查是否存在该题
        boolean checkWrongSubject   = checkWrongSubject(userId,subjectId);
        if (checkWrongSubject){
            //检查是否达标
            boolean checkRunNum = checkRunNum(userId,subjectId);
            if (checkRunNum){
                boolean deleteFileType = fileTypeService.deleteFileType(path,userId);
                boolean deleteWrongSubject = baseMapper.deleteWrongSubject(userId,subjectId);
                //是否删除成功
                if (deleteWrongSubject&&deleteFileType){

                    return 4; //删除成功
                }else {
                    return 3; //删除失败或被设置为不可删除
                }
            }else {
                return 5; //未达标做对该题次数
            }

        }else {
            return 6; //题目不存在
        }
    }


    /**
     * 删除分类文件路径时，进行删除错题文件
     * 获取对应路径下得所有错误题库
     */
    public int deleteWrongPath(String userId,String path){
        boolean deleteWrongPath = baseMapper.deleteWrongPath(userId,path);
        if (deleteWrongPath){
            return 0; //删除失败
        }else {
            return 1; //删除成功
        }

    }

    /**
     * 获取错题路劲得题库显示
     * @param pid
     * @param userId
     * @return
     */
    public List<Question> getWrongQuestion(String pid,String userId){
        List<Question> questions;
        questions = baseMapper.getWrongQuestion(pid,userId);
//        if (questions==null){
//            WrongSubject wrongSubject = baseMapper.checkWrongPath(userId,path);
//            if (wrongSubject==null){
//
//            }else {
//                deleteWrongPath(userId,path);
//            }
//        }
        return questions;
    }

    /**
     * 获取题库中的题目相关信息
     * @param quesBankModel
     * @param userId
     * @param questionId
     * @param currentPage
     * @param limit
     * @return
     */
    @Override
    public QuesBankModel getSubjectWithPage(QuesBankModel quesBankModel, String userId, String questionId, int currentPage, int limit) {
        QueryWrapper queryWrapper = new QueryWrapper();
//        queryWrapper.eq("userId", userId);
        queryWrapper.eq("questionId", questionId);
        /*获取分页数据*/
        Page<WrongSubject> page = new Page<>(currentPage,limit);
        IPage<WrongSubject> subIPage = baseMapper.selectPage(page, queryWrapper);
        ArrayList<WrongSubject> list = (ArrayList<WrongSubject>) subIPage.getRecords();

        //封装题目
        ArrayList<HandleImportModel> importModels = handleTrans(list,"question",0);

        //封装选项
        for (HandleImportModel model:importModels) {
            QueryWrapper queryWrapper1 = new QueryWrapper();
            queryWrapper1.eq("subjectId",model.getId());
            model.setChoiceList((ArrayList<SubjectChoiceType>) choiceTypeMapper.selectList(queryWrapper1));
        }
        quesBankModel.setHandleImportModels(importModels);
//        System.out.println(quesBankModel);
        return quesBankModel;
    }

    /**
     * 获取所有错题题目相关信息
     * 0 全部 1为 单选 2 为多选 3为判断 4填空
     * @param quesBankModel
     * @param userId
     * @param currentPage
     * @param limit
     * @return
     */
    @Override
    public QuesBankModel getAllSubjectWithPage(QuesBankModel quesBankModel, String userId,String questionId, int currentPage, int limit,int subjectType) {
        QueryWrapper queryWrapper = new QueryWrapper();
//        queryWrapper.eq("userId", userId);
        queryWrapper.eq("userId", userId);
        /*获取分页数据*/
        Page<WrongSubject> page = new Page<>(currentPage,limit);
        IPage<WrongSubject> subIPage = baseMapper.selectPage(page, queryWrapper);
        ArrayList<WrongSubject> list = (ArrayList<WrongSubject>) subIPage.getRecords();

        //封装题目
        ArrayList<HandleImportModel> importModels = handleTrans(list,"all",subjectType);
        if (importModels==null){
            return null;
        }
        //封装选项
        for (HandleImportModel model:importModels) {
            QueryWrapper queryWrapper1 = new QueryWrapper();
            queryWrapper1.eq("subjectId",model.getId());
            model.setChoiceList((ArrayList<SubjectChoiceType>) choiceTypeMapper.selectList(queryWrapper1));
        }
        quesBankModel.setHandleImportModels(importModels);
//        System.out.println(quesBankModel);
        return quesBankModel;
    }

    /**
     *  Subject 转化为  HandleImportModel
     */
    private ArrayList<HandleImportModel> handleTrans(ArrayList<WrongSubject> subList,String type,int selectType) {
        ArrayList<HandleImportModel> importModels = new ArrayList<>();
        for (WrongSubject wrongSubject : subList) {
            QueryWrapper queryWrapper1 = new QueryWrapper();
            queryWrapper1.eq("id",wrongSubject.getSubjectId());
            if (type.equals("all")){
                if (selectType!=0){
                    queryWrapper1.eq("typeId",selectType);
                }
            }
            Subject subject = subjectService.getOne(queryWrapper1);
            if (subject==null){
                continue;
            }
            HandleImportModel handleImportModel = new HandleImportModel();
            handleImportModel.setId(subject.getId());
            handleImportModel.setQuestionId(subject.getQuestionId());
            handleImportModel.setAnswer(subject.getAnswer());
            handleImportModel.setContent(subject.getContent());
            handleImportModel.setIsCollect(subject.getIsCollect());
            handleImportModel.setTypeId(subject.getTypeId());
            long score = subjectTypeService.getScore(subject.getTypeId());
            handleImportModel.setScore(score);
            importModels.add(handleImportModel);
        }
        return importModels;
    }
}
